﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jungle.Code.BLL;
using Jungle.Code.Utils;
using System.Collections.Generic;
using Jungle.Code.DAL;

using Jungle.Code.ProductManager;
using Jungle.Code.CategoryManager;

using System.Drawing;
using Jungle.Code.Core;
using Jungle.Users;
using Jungle.Code.News;
using Jungle.Modules;

namespace Jungle.Modules
{
    public partial class News_Admin : BaseAdminModule
    {
        int nid = 1;

        public override void FillBaseInfo()
        {
            sysName = "News";
        }
        public override void Main()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            SessionKeeper sk = new SessionKeeper();
            sk.SessionId = Session.SessionID;
            sk.GetData();

            UserManager user = new UserManager();
            user.UserId = sk.UserId;
            user.GetById();



            if (Request["nId"] != null)
                nid = Convert.ToInt32(Request["nId"]);

            switch (Request["cmd"])
            {
                case "add":
                    NewsView.ActiveViewIndex = 1;
                    btn_AddNewNews.Visible = true;
                    FillDdl();
                    break;
                case "view":
                    NewsView.ActiveViewIndex = 2;
                    FillDdl();
                    break;
                case "edit":
                    NewsView.ActiveViewIndex = 1;
                    btn_SaveNewsChanges.Visible = true;
                    FillDdl();
                    PrepareForEdit();
                    break;
                case "default":
                    NewsView.ActiveViewIndex = 0;
                    break;
                default:
                    NewsView.ActiveViewIndex = 0;
                    break;
            }


            base.OnInit(e);
        }

        public void PrepareForEdit()
        {
            News n = new News();
            n.IdNews = nid;
            n.GetById();

            txt_ProductDesc.Text = n.Body;
            txt_ProductTitle.Text = n.Title;
            ddl_NewsCategory.SelectedValue = n.CategoryId.ToString().Trim();

        }
        // --------------------------------------------------------------------------------------------
        public void FillDdl()
        {
            JungleTreeMenu cat = new JungleTreeMenu();


            cat.GetAll();
            ddl_NewsCategory.Items.Clear();
            foreach (JungleTreeMenu c in cat.MenuItemsList)
            {
                ListItem li = new ListItem(c.MenuText, c.ID.ToString());
                ddl_NewsCategory.Items.Add(li);
            }
        }
        // --------------------------------------------------------------------------------------------
        public void AddNews(object sender, EventArgs e)
        {
            string err = "";
            News n = new News();

            if (txt_ProductTitle.Text != "") { n.Title = txt_ProductTitle.Text; } else { err = "Заполните поле Заголовок"; }
            if (txt_ProductDesc.Text != "") { n.Body = txt_ProductDesc.Text; } else { err = "Заполните поле Текст новости"; }
            if (fu_Image.HasFile)
            {
                n.Img = SaveImage(fu_Image);
            }
            else
            {
                n.Img = "no_photo";
            }
            n.CategoryId = Convert.ToInt32(ddl_NewsCategory.SelectedValue);

            if (err != "") { lbl_ResultAddNews.Text = err; } else { n.Add(); Response.Redirect("Modules.aspx?mod=News&cmd=view"); }

        }
        // --------------------------------------------------------------------------------------------
        public string SaveImage(FileUpload file)
        {


            string mask = "qwertyuiopasdfghjklzxcvbnm";
            Random rnd = new Random();
            string rndstr = "";
            for (int i = 0; i < 6; i++)
            {
                rndstr += mask[rnd.Next(0, 24)];
            }
            string fnamePreview = "";
            string fnameLarge = "";
            try
            {
                System.Drawing.Image loadedImg = System.Drawing.Image.FromStream(file.PostedFile.InputStream);

                #region Preview

                fnamePreview = "/UserFiles/Images/Content/NewsImg/Preview/" + rndstr + file.FileName;

                int h = 170;
                int width = 100;

                double d1 = Math.Round((double)loadedImg.Width / width, 4);
                double d2 = Math.Round((double)loadedImg.Height / d1, 4);
                int height = Convert.ToInt32(d2);

                Bitmap imgOutput = new Bitmap(width, height);
                imgOutput.MakeTransparent();
                imgOutput.MakeTransparent(Color.Black);

                Graphics newGraphics = Graphics.FromImage(imgOutput);
                newGraphics.Clear(Color.FromArgb(0, 255, 255, 255));

                newGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                newGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newGraphics.DrawImage(loadedImg, 0, 0, width, height);
                newGraphics.Flush();

                if (file.FileName.ToLower().EndsWith(".jpg") || file.FileName.ToLower().EndsWith(".jpeg"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Jpeg);
                if (file.FileName.ToLower().EndsWith(".png"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Png);
                if (file.FileName.ToLower().EndsWith(".gif"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Gif);
                if (file.FileName.ToLower().EndsWith(".tiff"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Tiff);

                #endregion

                #region Large

                fnameLarge = "/UserFiles/Images/Content/NewsImg/Large/" + rndstr + file.FileName;

                if (Convert.ToInt32(Math.Round((double)loadedImg.Width, 4)) > 455)
                {
                    width = 455;
                }
                else
                {
                    width = Convert.ToInt32(Math.Round((double)loadedImg.Width, 4));
                }


                d1 = Math.Round((double)loadedImg.Width / width, 4);
                d2 = Math.Round((double)loadedImg.Height / d1, 4);
                height = Convert.ToInt32(d2);


                Bitmap imgOutput2 = new Bitmap(width, height);
                imgOutput2.MakeTransparent();
                imgOutput2.MakeTransparent(Color.Black);

                newGraphics = Graphics.FromImage(imgOutput2);
                newGraphics.Clear(Color.FromArgb(0, 255, 255, 255));

                newGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                newGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newGraphics.DrawImage(loadedImg, 0, 0, width, height);
                newGraphics.Flush();

                if (file.FileName.ToLower().EndsWith(".jpg") || file.FileName.ToLower().EndsWith(".jpeg"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Jpeg);
                if (file.FileName.ToLower().EndsWith(".png"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Png);
                if (file.FileName.ToLower().EndsWith(".gif"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Gif);
                if (file.FileName.ToLower().EndsWith(".tiff"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Tiff);


                #endregion
            }
            catch { fnamePreview = "ERROR"; }



            return fnamePreview + "," + fnameLarge;
        }
        // --------------------------------------------------------------------------------------------
        public void SaveChanges(object sender, EventArgs e)
        {
            string err = "";
            News n = new News();
            n.IdNews = nid;
            n.GetById();

            if (txt_ProductTitle.Text != "") { n.Title = txt_ProductTitle.Text; } else { err = "Заполните поле Заголовок"; }
            if (txt_ProductDesc.Text != "") { n.Body = txt_ProductDesc.Text; } else { err = "Заполните поле Текст новости"; }
            if (fu_Image.HasFile)
            {
                n.Img = SaveImage(fu_Image);
            }
            n.CategoryId = Convert.ToInt32(ddl_NewsCategory.SelectedValue);

            if (err != "") { lbl_ResultAddNews.Text = err; } else { n.Update(); lbl_ResultAddNews.Text = "Изменения сохранены." + n.err.ToString(); }
        }

    }
}